package com.yc.test.distributedLock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @Date: 2018/11/30 17:42
 * @Author: Can.Yang
 * @Description:mysql实现分布式锁
 */
public class MySqlLock implements Lock {

    /**
     * 阻塞式加锁
     */
    @Override
    public void lock() {
        //1.尝试加锁
        if (tryLock()) {
            return;
        }
        //2.加锁失败，当前任务休眠一段时间
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //3.递归调用lock(),再次重新加锁
        lock();
    }

    /**
     * 非阻塞式加锁，往数据库写入数据，能写成功的即加锁成功
     */
    @Override
    public boolean tryLock() {
        try {
            //mapper.insert(data)；
        } catch (Exception ex) {
            return false;
        }
        return true;
    }

    /**
     * 解锁
     */
    @Override
    public void unlock() {
        //mapper.delete(id);
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public Condition newCondition() {
        return null;
    }
}
